

jQuery.validator.addMethod("idCard", function(value, element) {
    var length = value.length;
    //15位和18位身份证号码的正则表达式  
    var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;  
    //如果通过该验证，说明身份证格式正确，但准确性还需计算  
    if (regIdCard.test(value)) {  
        if (value.length == 18) {  
            var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //将前17位加权因子保存在数组里  
           var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //这是除以11后，可能产生的11位余数、验证码，也保存成数组  
            var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和  
            for (var i = 0; i < 17; i++) {  
                idCardWiSum += value.substring(i, i + 1) * idCardWi[i];  
            }  
            var idCardMod = idCardWiSum % 11;//计算出校验码所在数组的位置  
            var idCardLast = value.substring(17);//得到最后一位身份证号码  
           //如果等于2，则说明校验码是10，身份证号码最后一位应该是X  
            if (idCardMod == 2) {  
                if (idCardLast == "X" || idCardLast == "x") {   
                	return this.optional(element) || true; 
                } else {
                    return this.optional(element) || false;  
                }  
            } else {  
                //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码  
                if (idCardLast == idCardY[idCardMod]) {   
                	return this.optional(element) || true;  
                } else {
                    return this.optional(element) || false; 
                }  
            }  
        }  
    } else {   
        return this.optional(element) || false;  
    }  
}, "请正确填写身份证号码");
$(function(){
	$("select").each(function(){
		$(this).append("<option value=''>---请选择---</option>");
	});
	var basePath = $("#basePath").val();
	$.ajax({
		url: basePath + "base_info/ajax_un_pigeonhole_base_data",
		type: "GET",
		dataType: "json",
		success: function( datas ) {
			console.log(datas);
			init(datas);
			
		}
	});
});

function init(baseInfo){
	var medicalDepts = baseInfo['medicalDepts'];
	$("select[name='outHospitalDeptCode'],[name='outDeptCode']").each(function(){
		var options = "";
		for(var index in medicalDepts){
			var medicalDept = medicalDepts[index];
	    	options+="<option value='"+medicalDept.uniq_code+"'>"+medicalDept.label+"</option>"
	    } 
       $(this).append(options);
       
	});
	
	var outHospitalTypes = baseInfo['outHospitalTypes'];
	$("select[name='outHospitalTypeCode']").each(function(){
		var options = "";
		for(var index in outHospitalTypes){
			var outHospitalType = outHospitalTypes[index];
	    	options+="<option value='"+outHospitalType.uniq_code+"'>"+outHospitalType.label+"</option>"
	    } 
       $(this).append(options);
	});
	
	$("input[name='isRelevance']").each(function(){
		
		$(this).dblclick(function(){
			$(this).removeAttr("checked");
		});
		
	});
}
/*点击查询按钮*/
function queryBtnClick(){
	$("input[name='currentPage']").val(1);
	queryFormSubmit();
}

/*提交查询*/
function queryFormSubmit(){
	var submitData = $('#queryForm').serialize();
	var basePath = $("#basePath").val();
	layer.load(1);
	
	clearPage();
	$.ajax({
		url: basePath + "upload_scan/ajax_upload_third_scan_query",
		dataType: "json",
		data:submitData,
		success: function( data ) {
			var success = data['success'];
			if(success){
				
				var params = data['data'];
				var totalCounts = params['totalCounts'];
				if(totalCounts > 0){
					layer.msg("查询成功");
					var records = params['datas'];
					addRows(records);
					var pageSize = params['pageSize'];
					var currentPage = params['currentPage'];
					initPage(parseInt(totalCounts),parseInt(pageSize),parseInt(currentPage));
				}else{
					layer.msg("查询结果为空");
				}
				
			}else{
				layer.msg("查询失败");
			}
			console.log(data);
			
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			layer.msg("未知错误，请联系管理员");
		},
		complete:function(XMLHttpRequest, textStatus){
			layer.closeAll('loading');
			parent.document.getElementById("mainContent").height=document.body.scrollHeight;
		}
	});
	
};

/*添加列表行*/
function addRows(records){
	var basePath = $("#basePath").val();
	for(var index in records){
		var record = records[index];
		var add_content=$("#template_tr").clone();
		add_content.removeAttr("hidden");
		add_content.attr("id",record.id);
		add_content.attr("visit_guid",record.visit_guid);
		add_content.find("span[class='folder_name']").html(record.upload_folder_name);
		add_content.find("span[class='upload_date']").html(record.upload_date_format);
		add_content.find("span[class='user_name']").html(record.upload_user_name);
		add_content.find("span[class='file_count']").html(record.file_count);
		var visit_guid = record.visit_guid;
		if(visit_guid){
			add_content.find("span[class='is_locked']").html("已关联");
			add_content.find("td[data-type='operate']").html("<a target='_blank' href='"+basePath+"medical_record_pagination/pagination_page?visitGuid="+visit_guid+"' title='病案编页'>病案编页&nbsp;</a> ");
			
		}else{
			add_content.find("span[class='is_locked']").html("未关联");
			/*add_content.find("td[data-type='operate']").html("<a target='_blank' href='"+basePath+"medical_record_coding/edit_index_info?visitGuid=' title='已进入编码'>已进入编码&nbsp;</a> ");
			*/
			add_content.find("td[data-type='operate']").html("<a onclick='medicalRecordRelevance(this)' title='病案关联'>病案关联&nbsp;</a>");
			
		}
		
		
		$("#query_show_table tbody").append(add_content);
    } 
	
}

/*清空列表和分页控件*/
function clearPage(){
	$("#template_tr").siblings("tr").remove();
	$("#page_plus").html("");
	$("#totalPage").html("0");
    $("#currentPage").html("0/0");
}

/*初始化分页控件*/
function initPage(totalCounts,pageSize,currentPage){
	 var visiblePages = 5;
	 var totalPages =  totalCounts%pageSize==0?(totalCounts/pageSize):(parseInt(totalCounts/pageSize)+1);
	 if(totalCounts < 1){
		$("#page_plus").html("");
		$("#totalPage").html("0");
        $("#currentPage").html("0/0");
	 }else{
		 $('#page_plus').jqPaginator({

	        totalCounts: totalCounts,
	        pageSize:pageSize,
	        visiblePages: visiblePages,
	        currentPage: currentPage,

	        first:'<li class="first"><a href="javascript:void(0);">首页</a></li>',
	        prev: '<li class="prev"><a href="javascript:void(0);">上一页</a></li>',
	        next: '<li class="next"><a href="javascript:void(0);">下一页</a></li>',
	        last: '<li class="last"><a href="javascript:void(0);">末页</a></li>',
	        page: '<li class="page"><a href="javascript:void(0);">{{page}}</a></li>',
	        onPageChange: function (num,type) {

	     		if(type !='init'){
	     			$("input[name='currentPage']").val(num);
	     			queryFormSubmit();
				}
	            $("#totalPage").html(totalCounts);
	            $("#currentPage").html(num+"/"+totalPages);
	        }
	    });
	 }
}

function medicalRecordRelevance(obj){
	var basePath = $("#basePath").val();
	var content = $(obj).parent().parent();
	var folder_name = content.find(".folder_name").html();
	var splits = folder_name.split('-');
	var uploadScanId = content.attr("id");
	var visit_guid = content.attr("visit_guid");
	var mrId = splits[0];
	var visitNumber = splits[1];
	$.ajax({
		url: basePath + "upload_scan/ajax_check_upload_relevance",
		dataType: "json",
		data:{mrId:mrId,visitNumber:visitNumber},
		success: function( data ) {
			var success = data['success'];
			if(success){
				
				var count = data['data'];
				if(count == 0){
					layerCreateRecord(obj);
				}else{
					medicalRecordRelevanceByMrIdAndVisitNumber(mrId,visitNumber,uploadScanId);
				}
				
			}else{
				layer.msg("关联失败");
			}
			console.log(data);
			
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			layer.msg("未知错误，请联系管理员");
		},
		complete:function(XMLHttpRequest, textStatus){
			layer.closeAll('loading');
		}
	});
	
	
}

function medicalRecordRelevanceByMrIdAndVisitNumber(mrId,visitNumber,uploadScanId){

	var submitData = $('#addForm').serialize();
	var basePath = $("#basePath").val();
	layer.load(1);
	$.ajax({
		url: basePath + "upload_scan/ajax_medical_record_relevance",
		type: "POST",
		dataType: "json",
		data:{mrId:mrId,visitNumber:visitNumber,uploadScanId:uploadScanId},
		success: function( data ) {
			var success = data['success'];
			if(success){
				var stateCode = data['stateCode'];
				if("1" == stateCode){
					layer.msg("关联成功！");
					var visitGuid = data['data'];
					relevanceSuccess(uploadScanId,visitGuid);
				}
				else{
					layer.msg("未预期错误！");
				}
			}else{
				layer.msg("操作错误，请重试！");
			}
			console.log(data);
			
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			if(XMLHttpRequest.status == 200){
				if(textStatus == 'parsererror'){
					layer.msg("登陆已过期，请重新登陆");
				}else{
					layer.msg("未知错误，请联系管理员");
				}
			}else if(XMLHttpRequest.status == 0){
				if(textStatus == 'error'){
					layer.msg("无法连接服务器，请检测网络");
				}else{
					layer.msg("未知错误，请联系管理员");
				}
			}else{
				layer.msg("未知错误，请联系管理员");
			}
		},
		complete:function(XMLHttpRequest, textStatus){
			layer.closeAll('loading');
		}
	});

}

function layerCreateRecord(obj){
	//页面层
	var add_content=$("#layer_create_record").clone();
	add_content.find("form").attr("id","addForm");
	addFormIndex = layer.open({
	  type: 1,
	  title:'新增病案',
	  skin: 'layui-layer-rim', //加上边框
	  area: ['320px', '450px'], //宽高
	  content: add_content.html(),
	  success: function(layero, index){
		  var content = $(obj).parent().parent();
		  var folder_name = content.find(".folder_name").html();
		  var splits = folder_name.split('-');
		  var uploadScanId = content.attr("id");
		  $("#addForm input[name='uploadScanId']").val(uploadScanId);
		  $("#addForm input[name='mrId']").val(splits[0]);
		  $("#addForm input[name='visitNumber']").val(splits[1]);
		  $("#addForm select[name='outDeptCode'],[name='outHospitalTypeCode']").each(function(){
			$(this).change(function(){
		   		var eventObj = $(this);
		   		var nameObjName = eventObj.attr("name").replace("Code", "Name");
		   		
		   		if(eventObj.val()!=""){
		   			var name=eventObj.find("option:selected").text();
		   			eventObj.next("input[name='"+nameObjName+"']").val(name);
		   		}else{
		   			eventObj.next("input[name='"+nameObjName+"']").val("");
		   		}
			});
		  });
		  
		  $("#addForm input,select").each(function() {
			  $(this).attr("id",$(this).attr("name"));
		  })
		  
		  var validator = $("#addForm").validate({
				errorElement: "title",
				ignoreTitle: true,
				submitHandler : function(){
					addFormSubmit();
				},
				rules:{
					onlyId: {
		                minlength: 6,
		                maxlength: 20,
		            },
					patientName: {
		                minlength: 2,
		                maxlength: 8,
		                required: true
		            },
		            idNumber: {
		                idCard:true
		            },
					mrId: {
		                minlength: 5,
		                maxlength: 20,
		                required: true
		            },
		            visitNumber: {
		            	range:[1,2000],
		            	digits:true,
		                required: true
		            },
		            outDeptCode: {
		                required: true
		            },
		            outHospitalDateTime: {
		                required: true,
		                date:true
		            },
		            outHospitalTypeCode: {
		                required: true
		            }
		            
				},
				
			});
	  }
	});
}

function clickAddFormSubmitBtn(){
	$('#addForm').submit();
}

function addFormSubmit(){
	var submitData = $('#addForm').serialize();
	var basePath = $("#basePath").val();
	var uploadScanId = $("#addForm input[name='uploadScanId']").val();
	layer.load(1);
	$.ajax({
		url: basePath + "upload_scan/ajax_add_medical_record_relevance",
		type: "POST",
		dataType: "json",
		data:submitData,
		success: function( data ) {
			var success = data['success'];
			if(success){
				var stateCode = data['stateCode'];
				if("2" == stateCode){
					layer.msg("该病案已存在！");
					
				}else if("1" == stateCode){
					var visitGuid = data['data'];
					relevanceSuccess(uploadScanId,visitGuid);
					layer.msg("关联成功！");
					layer.close(addFormIndex);
				}
				else{
					layer.msg("未预期错误！");
				}
			}else{
				layer.msg("操作错误，请重试！");
			}
			console.log(data);
			
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			if(XMLHttpRequest.status == 200){
				if(textStatus == 'parsererror'){
					layer.msg("登陆已过期，请重新登陆");
				}else{
					layer.msg("未知错误，请联系管理员");
				}
			}else if(XMLHttpRequest.status == 0){
				if(textStatus == 'error'){
					layer.msg("无法连接服务器，请检测网络");
				}else{
					layer.msg("未知错误，请联系管理员");
				}
			}else{
				layer.msg("未知错误，请联系管理员");
			}
		},
		complete:function(XMLHttpRequest, textStatus){
			layer.closeAll('loading');
		}
	});
}

/*添加列表行*/
function relevanceSuccess(uploadScanId,visitGuid){
	var basePath = $("#basePath").val();
	var add_content=$("#query_show_table tr[id='"+uploadScanId+"']");
	add_content.find("span[class='is_locked']").html("已关联");
	add_content.find("td[data-type='operate']").html("<a target='_blank' href='"+basePath+"medical_record_pagination/pagination_page?visitGuid="+visitGuid+"' title='病案编页'>病案编页&nbsp;</a> ");
	
}
